package com.wuchengdong.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuchengdong.web.extend.utils.R;
import com.wuchengdong.web.pojo.Review;
import com.wuchengdong.web.service.AppointmentService;
import com.wuchengdong.web.service.ReviewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/review")
public class ReviewController {
    @Autowired
    private ReviewService reviewService;
    @Autowired
    private AppointmentService appointmentService;

    @GetMapping
    public R<List<Review>> getAll() {
        return R.success(reviewService.list());
    }

    /**
     * 一个预约ID 对应这唯一的用户享受了唯一的服务，只能有一条评价
     */
    @GetMapping("/getByAppointmentId")
    public R<Review> getByAppointmentId(Review review) {
        return R.success(reviewService.getOne(
                new LambdaQueryWrapper<Review>()
                        .eq(Review::getAppointmentId, review.getAppointmentId())
        ));
    }

    /**
     * 一个服务的所有评价
     */
    @GetMapping("/getByServiceId")
    public R<List<Review>> getByServiceId(Review review) {
        return R.success(reviewService.list(
                new LambdaQueryWrapper<Review>()
                        .eq(Review::getServiceId, review.getServiceId())
                        .orderByDesc(Review::getCreatedAt)
        ));
    }

    @GetMapping("/getReviewList")
    public R<List<Map<String, String>>> getReviewList(@RequestParam int page) {
        return R.success(reviewService.getReviewList(page));
    }

    @PostMapping
    public R<String> saveOrUpdate(@RequestBody Review review) {
        if (review.getAppointmentId() == null || review.getUserId() == null) {
            return R.error("用户ID 预约ID不能为空");
        }
        if (review.getServiceId() == null) {
            Integer serviceId = appointmentService.getById(review.getAppointmentId()).getServiceId();
            review.setServiceId(serviceId);
        }
        reviewService.saveOrUpdate(review);
        return R.success("评价成功");
    }

    @DeleteMapping
    public R<String> delete(Review review) {
        return reviewService.removeById(review.getId()) ? R.success("删除成功") : R.error("删除失败");
    }
}
